/**
 * @author VernHe
 * @date 2021年04月01日 23:43
 */
public class Solution_1143 {
    public static void main(String[] args) {
        System.out.println(longestCommonSubsequence("bsbininm", "jmjkbkjkv"));
    }
    public static int longestCommonSubsequence(String text1, String text2) {
        // 参数判断
        if (text1 == null || text2 == null) return 0;
        char[] char1 = text1.toCharArray();
        char[] char2 = text2.toCharArray();
        if (char1.length == 0 || char2.length == 0) return 0;
        char[] rowChar = char1;
        char[] colChars = char2;
        if (char2.length > char1.length) {
            // 短的作为列
            colChars = char1;
            rowChar = char2;
        }
        // dp数组
        int[] dp = new int[colChars.length + 1];
        // 不用初始化dp[0][0]、dp[0][1]、dp[1][0]，因为默认就是0
        for (int i = 1; i <= rowChar.length; i++) {
            // 记录leftTop
            int cur = 0;
            for (int j = 1; j <= colChars.length; j++) {
                int leftTop = cur;
                cur = dp[j];
                if (rowChar[i - 1] == colChars[j - 1]) {
                    dp[j] = leftTop + 1;
                } else {
                    dp[j] = Math.max(dp[j], dp[j - 1]);
                }
            }
        }
        return dp[colChars.length];
    }
}
